var param = {}, formId = 'queryForm', url = "/openx/order/queryService/listOrderPick", orderDetail = {};
/**新增*/
var rowindex = 100;
var days = 30;
var orderCode = null;
var intervalDays = 7;
var allowConsortGoBack = false;
var allowTransferReject = true;
var selectedSale="";

//点击查询按钮调用
$.openx.query = function () {
    try{
        getSystemParam();
    }catch (e) {
        console.info(e)
    }
    var createStartTime = new Date($("#createStartTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#createEndTime").val().replace(/\-/g, "\/"));
    getDaysByMonth(createStartTime.getFullYear(), createStartTime.getMonth() + 1);
    if (createStartTime > createEndTime) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    createStartTime = new Date(createStartTime.setDate(createStartTime.getDate() + intervalDays));
    var orderCode = $("input[name='orderCode']").val();
    var parentOrderCode = $("input[name='parentOrderCode']").val();
    var outTradeCode = $("input[name='outTradeCode']").val();
    var receiverPhone = $("input[name='receiverPhone']").val();
    if (orderCode.trim() === '' && parentOrderCode.trim() === '' && outTradeCode.trim() === '' && receiverPhone.trim() === '') {
        if (isNaN(createStartTime.getTime())) {
            layer.msg('开始时间不能为空！');
            return false;
        }
        if (isNaN(createEndTime.getTime())) {
            layer.msg('结束时间不能为空！');
            return false;
        }
        if (createStartTime < createEndTime) {
            layer.msg('选择的时间区间必须在' + intervalDays + '天以内');
            return false;
        }
    }
    if(receiverPhone){
        if(receiverPhone.length<3){
            layer.msg('至少输入三位手机号码');
            return false;
        }
    }
    //状态重置
    var orderStaus = $("input[name='orderStatus']").val();
    if (orderStaus != '') {
        //异常状态
        $("#deliveryStatus").val(orderStaus === 'DELIVERY_EXCEPTION' && orderStaus != 'ALL' ? orderStaus : '');

        //待下账
        $("#postingStatus").val(orderStaus === 'WAITING_POSTING' && orderStaus != 'ALL' ? orderStaus : '');

        //退款中 和已退货
        $("#refundStatus").val((orderStaus === '2' || orderStaus === '1') && orderStaus != 'ALL' ? orderStaus : '');

        //待自提
        $("#deliveryType").val(orderStaus === 'SELF_PICK' && orderStaus != 'ALL' ? orderStaus : '')

        if (orderStaus === 'DELIVERY_EXCEPTION' || orderStaus === 'WAITING_POSTING' || orderStaus === '2' || orderStaus === '1' || orderStaus === 'ALL' || orderStaus === 'SELF_PICK') {
            $("input[name='orderStatus']").val('');
        }
    }
    var data = $.openx.getJsonObj(formId);
    param.order = data;
    var equryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
    $('#table').bootstrapTable({pageList: [10, 25, 50]});
}

/**
 * 完善用户信息
 */
function fillingCustomerInfo() {

    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    var regPhone1 = /^1\d{10}$/;
    var regPhone2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    var receiver = orderDetail.receiver || {};
    var additionalInfos = orderDetail.additionalInfos || [];
    receiver.remark = orderDetail.remark || '';
    if (additionalInfos.length > 0) {
        $.each(additionalInfos, function (index, val) {
            if (val.infoCode === 'idCard') {
                // infoValue
                if (regIdCard.test(val.infoValue)) {
                    receiver.idCard = val.infoValue;
                }
            }
        })
    }
    if (orderDetail.receiver.name == undefined || orderDetail.receiver.name === '' || orderDetail.receiver.name === '-') {
        receiver.name = '';
    }
    receiver.phoneTest = false;
    if (orderDetail.receiver.phone == undefined || orderDetail.receiver.phone === '' || orderDetail.receiver.phone === '-') {
        receiver.phone = '';
    } else {
        if (regPhone1.test(orderDetail.receiver.phone) || regPhone2.test(orderDetail.receiver.phone)) {
            receiver.phone = orderDetail.receiver.phone;
            receiver.phoneTest = true;
        } else if (orderDetail.receiver.phone.length > 0) {
            receiver.phone = orderDetail.receiver.phone;
        } else {
            receiver.phone = "";
        }
    }
    var html = $.openx.innerHtml('fillingCustomerInfoTpl');
    laytpl(html).render(receiver, function (renderHtml) {
        var fillingCustomerInfoTplIndex = $.openx.openLayer(['600', '330'], '完善信息', renderHtml, true, function () {
            var obj = $.openx.getJsonObj('fillingCustomerInfoForm');
            var info = {};
            if (obj != undefined) {
                if (obj.receiverName != undefined) {
                    if (obj.receiverName.length != 0 && obj.receiverName.trim().length < 1 && obj.receiverName.trim().length < 10) {
                        layer.tips("姓 名 填 写 错 误", '#receiverNameFill');
                        return;
                    }
                }
                if (obj.receiverPhone != undefined) {
                    if (regPhone1.test(obj.receiverPhone) || regPhone2.test(obj.receiverPhone)) {

                    } else if (obj.receiverPhone.length == 0) {

                    } else if (obj.receiverPhone === orderDetail.receiver.phone) {
                        obj.receiverPhone = '';
                    } else {
                        layer.tips("电 话 号 码 不 符 合 要 求", '#receiverPhoneFill');
                        return;
                    }
                }
                if (obj.receiverIdCard != undefined) {
                    if (regIdCard.test(obj.receiverIdCard)) {

                    } else if (obj.receiverIdCard.length == 0) {

                    } else {
                        layer.tips("身 份 证 号 码 不 符 合 要 求", '#receiverIdCardFill');
                        return;
                    }
                }
                if (((obj.receiverIdCard != undefined && obj.receiverIdCard.length == 0) || obj.receiverIdCard == undefined) &&
                    ((obj.receiverPhone != undefined && obj.receiverPhone.length == 0) || obj.receiverPhone == undefined) &&
                    ((obj.receiverName != undefined && obj.receiverName.length == 0) || obj.receiverName == undefined) &&
                    ((obj.receiverRemark != undefined && obj.receiverRemark.length == 0) || obj.receiverRemark == undefined)
                ) {
                    // layer.msg("没有效值！");
                    return;
                }
                $X("/order/operateService", "updateCustomerInfo").callx({
                    orderCode: orderDetail.orderCode,
                    receiverName: obj.receiverName ? obj.receiverName : '',
                    receiverPhone: obj.receiverPhone ? obj.receiverPhone : '',
                    receiverIdCard: obj.receiverIdCard ? obj.receiverIdCard : '',
                    receiverRemark: obj.receiverRemark ? obj.receiverRemark : '',
                    onResult: function (result) {
                        if (result) {
                            layer.msg("修改成功")
                            setTimeout(function () {
                                layer.closeAll();
                                showOrderDetail(orderDetail);
                            }, 1000);

                        } else {
                            layer.msg("修改失败")
                        }
                    },
                    onError: function (error) {
                        layer.msg(JSON.parse(error).message);
                    }
                });
            }
        });
    });
}

$(window).load(function(){
    $X("/order/queryService", "checkIsOpenMessage").callx({
        onResult: function (result) {
            if(result){
                var nowDate  = new Date(laydate.now());
                getDaysByMonth(nowDate.getFullYear(),nowDate.getMonth());
                var createStartTime = laydate.now(-6) + ' 00:00:00';
                var createEndTime = laydate.now() + ' 23:59:59';
                $X("/order/queryService", "getPostingOrderCount").callx({
                    createStartTime: createStartTime,
                    createEndTime: createEndTime,
                    onResult: function (result) {
                        if(result && result > 0){
                            layer.confirm('检测到'+result+'条未下账订单，是否查看',{
                                btn: ['查看','取消'] //按钮
                                ,skin:'layui-layer-molv'
                            }, function () {
                                layer.closeAll('dialog');
                                document.getElementById('createStartTime').value= createStartTime;
                                document.getElementById('createEndTime').value= createEndTime;
                                $(".btn-warning").click();
                            });
                        }
                    },
                    onError: function (error) {

                    }
                });
            }
        },
        onError: function (error) {

        }
    });

    getSystemParam()
});


//初始化日期控件时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    if (UrlParameter()['orderCode'] != '' && UrlParameter()['orderCode'] != null) {
        document.getElementById('createStartTime').value = '';
        document.getElementById('createEndTime').value = '';
        var data = $.openx.getJsonObj(formId);
        data.orderCode = UrlParameter()['orderCode'];
    } else {
        document.getElementById('createStartTime').value = laydate.now(-1) + ' 00:00:00';
        document.getElementById('createEndTime').value = laydate.now() + ' 23:59:59';
        var data = $.openx.getJsonObj(formId);
    }
    param.order = data;
    console.log(param.order);
    $.openx.initTable("table", url, param, null, [10, 25, 50]);
});

// 点击订单状态查询订单信息
var previousObj = $("button[name='orderStatus']")[0];
$("button[name='orderStatus']").on('click', function (e) {
    var $this = e.currentTarget;
    $("input[name='orderStatus']").val($this.value);
    if (previousObj != $this) {
        $($this).find('i').addClass("glyphicon glyphicon-ok-sign")
        $(previousObj).find('i').removeClass('glyphicon glyphicon-ok-sign');
    }
    previousObj = $this;
    $.openx.query();
})

//查看订单详情
function showOrderPickDetail(row) {
    var html = $.openx.innerHtml('orderDetailTpl');
    $X("/order/queryService", "getOrderPickDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver;
            if (receiver) {
                result.receiverName = receiver.name
                result.receiverPhone = receiver.phone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "");
            }
            result.createTime = $.openx.formatDate(new Date(result.createTime));
            // result.showRecipeBtn = false;
            // if (result.parentOrderCode != undefined && (result.topChannelCode === 'PABC' || result.topChannelCode === 'PAHYS')) {
            //
            //     //检查是否显示查看处方单按钮
            //     var url = prescript_detail_url + result.parentOrderCode + ".pdf";
            //
            //     $.ajax({
            //         type: "GET",
            //         url: url,
            //         async: false,
            //         success: function (res) {
            //             result.showRecipeBtn = true;
            //         },
            //         error: function (res) {
            //             result.showRecipeBtn = false;
            //         }
            //     });
            // }
            laytpl($.openx.innerHtml('orderDetailTpl')).render(result, function (html) {
                $.openx.openLayer(null, '订单详情', html, true);
            });
            //当前订单详细对象
            orderDetail = result;
        },
        onError: function (error) {

        }
    });
}

function queryLogistics() {
    $X("/logistics/logisticsListService", "listDeliveryTask").callx({
        orderCode: orderDetail.orderCode,
        onResult: function (result) {
            if (!result) {
                result = [{}];
            }
            layer.closeAll('loading')
            laytpl($.openx.innerHtml('logisticsInfotpl')).render(result, function (html) {
                $.openx.openLayer(null, '物流跟踪详情', html, true);
            });
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}

function showPickRecipe(topChannelCode) {
    // if (topChannelCode == undefined || topChannelCode == null || topChannelCode !== 'PAHYS' || topChannelCode !== 'PABC') {
    //     if (orderDetail.ordonnanceId != undefined) {
    //         var url = prescriptWebHtml + '?orderCode=' + orderDetail.parentOrderCode;
    //         layer.open({
    //             content: [url],
    //             type: 2,
    //             title: '查看处方',
    //             area: ['1000px', '500px']
    //         });
    //     }
    // }
    // if (topChannelCode === 'PAHYS' || topChannelCode === 'PABC') {
    //     var url = prescript_detail_url + orderDetail.parentOrderCode + ".pdf";
    //     window.location.href = url;
    // }


    if (topChannelCode === 'PAHYS' || topChannelCode === 'PABC' || topChannelCode === 'DSJK' || topChannelCode === 'KWZY'|| topChannelCode === 'XLYG'
        || topChannelCode === 'NEB' || topChannelCode === 'FXJK' || topChannelCode === 'FXJKBC' || topChannelCode === 'CXKJ' || topChannelCode === 'ELEMEBC') {
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".pdf";
        window.location.href = url;
    }else if(topChannelCode === 'JDDJ'  || topChannelCode === 'YYW'){
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".jpg";
        window.location.href = url;
    }else if(topChannelCode === 'XRQEYS' || topChannelCode === 'XINGREN'){
        if (orderDetail.ordonnanceId !== undefined) {
            var url = ecp_boss_logistics_tpl_url+"/html/order/prescriptionDetail.html?prescriptionId=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    } else if (topChannelCode === 'YFJX' || topChannelCode === 'ZHEBOTO' || topChannelCode === 'JDYJS' || topChannelCode === 'JDYJSBC'|| topChannelCode === 'YSQYJK' || topChannelCode === 'YSQYJKBC'|| topChannelCode === 'JKXB' || topChannelCode === 'YFYS' || topChannelCode === 'XR') {
        if (orderDetail.ordonnanceId !== undefined) {
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    } else{
        //if(topChannelCode == undefined || topChannelCode == null){
        if (orderDetail.ordonnanceId != undefined) {
            // var url = prescriptWebHtml + '?orderCode=' + orderDetail.parentOrderCode;
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
        //}
    }
}

function loodPrescript(url){
    layer.open({
        content: [url],
        type: 2,
        title: '查看处方',
        area: ['1000px', '500px']
    });
}

function printlnTicketNotify(row){
    if (row.ticketPrinted || row.autoPosting) {
        $.openx.confirm('请先完成拣货，确认订单内商品门店是否有实物库存', function () {
            layer.closeAll('dialog');
            printlnTicket(row);
        });
    } else {
        querySalesCodes(row);
    }
}

//单独打印小票
function printlnTicket(row) {
    if (row) {
        var orderCode = ""
        var orderCodes = []
        var stateCode = row.stateCode
        if (stateCode === 'DELIVERY_WAITING' || stateCode === 'RECEIVE_WAITING' || stateCode === 'ORDER_FINISH') {
            orderCodes.push(row.orderCode)
            orderCode = row.orderCode + ","
            if (row.ticketPrinted) {
                $.openx.confirm('小票已打印，是否需重新打印？', function () {
                    layer.closeAll('dialog');
                    openTicketDialog(orderCode);
                });
            } else {
                // 如果是自动下账
                if(row.autoPosting) {
                    if (row.topChannelCode === 'POS') {
                        autoCreateConsort(row);
                        return;
                    } else {
                        autoCreatePosting(row);
                        return ;
                    }
                }
                //1、判断是否是自提单
                if (row.stateCode === 'DELIVERY_WAITING' && row.deliveryType === 'SELF_PICK') {
                    openTicketDialog(orderCode, orderCodes);
                    return;
                }
                if (row.stateCode === 'DELIVERY_WAITING' && row.deliveryProvider) {//待发货并且是益丰配送则请求物流平台进行发货处理
                    $.openx.confirm('打印小票，同时会进行发货操作。是否继续？', function () {
                        layer.closeAll('dialog');
                        //通知物流平台进行发货操作
                        var newWindow = window.open();
                        $X("/order/operateService", "createOrderDeliveryTask").callx({
                            orderCode: orderCodes[0],
                            onResult: function (result) {
                                if (result === 0) {
                                    layer.closeAll();
                                    openTicketDialog(orderCode, orderCodes,null,newWindow);
                                } else {
                                    layer.msg('发货失败，请联系管理员!');
                                }
                            },
                            onError: function (error) {
                                layer.msg(error.msg);
                            }
                        });


                    });
                } else {
                    openTicketDialog(orderCode, orderCodes)
                }
            }
        } else {
            layer.msg("不能选择【" + row.state + "】的订单进行小票打印", {time: 3000, icon: 5});
            return
        }
    }
}

function printTicketNotify(row){
    $.openx.confirm('请先完成拣货，确认订单内商品门店是否有实物库存', function () {
        layer.closeAll('dialog');
        printTicket(row);
    });
}

//仅打小票，不做其他操作
function printTicket(row) {
    if (row) {
        var orderCode = ""
        var orderCodes = []
        var stateCode = row.stateCode
        if (stateCode === 'DELIVERY_WAITING' || stateCode === 'RECEIVE_WAITING' || stateCode === 'ORDER_FINISH') {
            orderCodes.push(row.orderCode)
            orderCode = row.orderCode + ","
            openTicketDialog(orderCode, orderCodes, "N");

        } else {
            layer.msg("不能选择【" + row.state + "】的订单进行小票打印", {time: 3000, icon: 5});
            return
        }
    }
}

/**
 * isInsertPrintRecord  是否插入打印记录
 * 如果传入空值,或不传则会打印记录，
 * 否则就只打印小票不插入记录
 * */
function openTicketDialog(orderCode, orderCodes, isInsertPrintRecord,newWindow) {
    if (orderCodes && !isInsertPrintRecord) {
        insertPrintRecord(orderCodes, 'Y', null, null);
    }
    // var newWindow = window.open();
    // newWindow.location.href = "../../html/order/printlnTicket.html?orderCode=" + orderCode;
    window.open("../../html/order/printlnTicket.html?orderCode=" + orderCode)
}


function batchPrintlnTickeBefore() {

    let warehouseCodeSet = new Set();

    //已选择的行信息
    var selectedRow = $.openx.getSelectedRow();

    //批量打印逻辑
    if (selectedRow && selectedRow.length == 0) {
        layer.msg("请选择需要打印的小票")
        return;
    }

    if (selectedRow && selectedRow.length > 50) {
        layer.msg("小票批量打印不能超过50条");
        return;
    }

    for (let i = 0; i < selectedRow.length; i++) {
        console.log(JSON.stringify(selectedRow[i]));
        warehouseCodeSet.add(selectedRow[i].warehouseCode);
    }

    if(warehouseCodeSet.size>1){
        layer.msg("所有订单必须属于同一个门店");
        return;
    }


    var orderRow = selectedRow[0];
    var html = $.openx.innerHtml('salesCodesTpl4BatchPrintlnTicket');
    ajax(jot_posting_server + "/posting/postingQueryService", "querySalesCodes").callx({
        orderCode: orderRow.orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            laytpl($.openx.innerHtml('salesCodesTpl4BatchPrintlnTicket')).render(result, function (html) {
                $.openx.openLayer(null, '打印小票', html, true);
            });

            var exist = false;
            $("#salesCodeSelect4BatchPrintlnTicket option").each(function(){
                var txt = $(this).val();   //获取option值
                if(txt==selectedSale){
                    exist =true;
                }
            });

            if(exist){
                $("#salesCodeSelect4BatchPrintlnTicket").val(selectedSale);
            }

        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });

}


function saveOperatorCodes4BatchPrintlnTicket() {

    var salesCodeSelect4BatchPrintlnTicket = $("#salesCodeSelect4BatchPrintlnTicket").val();
    if (salesCodeSelect4BatchPrintlnTicket === '') {
        layer.tips("营 业 员 不 能 为 空", '#salesCodeSelect4BatchPrintlnTicket');
        return ;
    }


    selectedSale = salesCodeSelect4BatchPrintlnTicket;

    //已选择的行信息
    var selectedRow = $.openx.getSelectedRow()

    //批量打印逻辑
    if (selectedRow && selectedRow.length == 0) {
        layer.msg("请选择需要打印的小票")
        return;
    }

    if (selectedRow && selectedRow.length > 50) {
        layer.msg("小票批量打印不能超过50条");
        return;
    }

    for (let i = 0; i < selectedRow.length; i++) {
        var idxrow = selectedRow[i];
        var postingModel = {};
        postingModel.orderCode = idxrow.orderCode;
        postingModel.operatorCode = salesCodeSelect4BatchPrintlnTicket;
        ajax(jot_posting_server + "/posting/postingService", "savePostingModel").callx({
            postingModel: postingModel,
            onResult: function (result) {
                console.info("保存下账数据成功");
            },
            //请求失败执行
            onError: function (error) {
                console.info(error);
                layer.msg("保存下账数据失败: " + error);
            }
        });
    }
    layer.closeAll();

}


//批量打印  待发货 、 待收货、 已完成
function batchPrintlnTicket() {

    //add by zhouwk
    saveOperatorCodes4BatchPrintlnTicket();

    var orderCode = ""

    //批量发货的订单数组
    var orderCodes = []

    //批量打印小票的数字
    var printOrderCode = []

    //已选择的行信息
    var selectedRow = $.openx.getSelectedRow()

    //批量打印逻辑
    if (selectedRow && selectedRow.length == 0) {
        layer.msg("请选择需要打印的小票")
        return;
    }

    if (selectedRow && selectedRow.length > 50) {
        layer.msg("小票批量打印不能超过50条");
        return;
    }

    for (let i = 0; i < selectedRow.length; i++) {
        console.log("@@@@@@@@@@@@@@@@"+JSON.stringify(selectedRow[i]));
    }

    //检查选择的行中 如果有待发货状态的订单则进行发货提示， 即判断是都需要发货
    var isNeedDelivery = false; //是否需要进行发货操作
    for (var x = 0; x < selectedRow.length; x++) {

        var stateCode = selectedRow[x].stateCode
        var currCode = selectedRow[x].orderCode

        if (selectedRow[x].logisticsId === '自提') {
            continue;
        }

        if (stateCode === 'DELIVERY_WAITING' || stateCode === 'RECEIVE_WAITING' || stateCode === 'ORDER_FINISH') {
            //打印的
            orderCode += currCode + ","
            printOrderCode.push(currCode)
        } else {
            layer.msg("不能选择【" + selectedRow[x].state + "】的订单进行小票打印", {time: 3000, icon: 5});
            return
        }
        //发货的
        if (stateCode === 'DELIVERY_WAITING') {
            isNeedDelivery = true
            orderCodes.push(currCode);
        }
    }


    if (isNeedDelivery) {
        $.openx.confirm("是否批量处理本页" + orderCodes.length + "条未发货订单，确认后，进行批量打印小票。", function () {
            layer.closeAll('dialog');
            $X("/order/operateService", "createOrderBatchDeliveryTask").callx({
                orderCodes: orderCodes,
                onResult: function (result) {
                    var faidCount = orderCodes.length;
                    if (result && result.length > 0) {
                        faidCount = orderCodes.length - result.length;
                        layer.msg("共打印" + orderCodes.length + "笔，成功" + result.length + "笔，失败 " + faidCount + "笔，打印失败的订单请点击'未发货'按钮进行查看。")
                        setTimeout(function () {
                            //记录小票打印记录
                            openTicketDialog(result.toString(), result)
                        }, 3000);
                        $.openx.tableRefresh(null, null, true);
                    } else {
                        layer.msg("打印全部失败，请点击'未发货'按钮进行查看。")
                    }
                },
                //请求失败执行
                onError: function (error) {
                    layer.msg("发货失败")
                    $.openx.tableRefresh(null, null, true);
                }
            });
        });
    } else {
        if (orderCode.length > 0 && printOrderCode.length > 0) {
            openTicketDialog(orderCode, printOrderCode)
        }
    }
}


//打印处方
function printPrescription(row) {
    if (row) {
        var orderCode = row.orderCode;
        if (orderCode) {

            //标记处方单打印记录
            var orderCodes = [];
            orderCodes.push(orderCode);
            insertPrintRecord(orderCodes, null, 'Y', null);
            window.open(prescriptWeb + "/prescription.html?orderCode=" + row.parentOrderCode);
        }
    }
}

// 打印用法用量
function printUsageAndDosage(row) {
    var orderCode = row.orderCode;
    if (orderCode) {
        //标记用法用量打印记录
        var orderCodes = [];
        orderCodes.push(orderCode);
        insertPrintRecord(orderCodes, null, null, 'Y');

        window.open(prescriptWeb + "/printDosage.html?orderCode=" + row.parentOrderCode);
    }
}


//插入打印记录 标记那个订单是否打印 type :
function insertPrintRecord(orderCodes, ticketPrinted, prescriptionPrinted, dosagePrinted) {

    var form = {
        orderCodes: orderCodes,
        ticketPrinted: ticketPrinted ? ticketPrinted : '',
        prescriptionPrinted: prescriptionPrinted ? prescriptionPrinted : '',
        dosagePrinted: dosagePrinted ? dosagePrinted : '',
    }
    $X("/order/operateService", "createOrderPrintRecord").callx({
        form: form,
        onResult: function (result) {
            layer.closeAll('loading')
            setTimeout(function () {
                $.openx.tableRefresh(null, null, true)
            }, 2000);
        },
        onError: function (error) {
        }
    });
}


//查询下账信息
function queryPostingDetail(row) {
    var html = $.openx.innerHtml('postingTpl');
    $X("/order/queryService", "getOrderPickDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver;
            if (receiver) {
                result.receiverName = receiver.name
                result.receiverPhone = receiver.phone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "");
            }
            result.createTime = $.openx.formatDate(new Date(result.createTime));
            orderDetail = result;
        },
        onError: function (error) {
        }
    });

    ajax(jot_posting_server + "/posting/postingQueryService", "queryPostingDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            orderCode = result.orderCode;
            laytpl($.openx.innerHtml('postingTpl')).render(result, function (html) {
                $.openx.openLayer(null, '下账', html, true);

                $('#storeUserSelect').change(function () {
                    if ($(this).val() === 'other') {
                        $('#otherStoreUserLabel').show();
                        $('#otherStoreUserInput').show();
                    } else {
                        $('#otherStoreUserLabel').hide();
                        $('#otherStoreUserInput').hide();
                    }
                });
            });
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}


function addRowsData(curr, tr) {
    rowindex = parseInt($(tr).attr("data-index")) + rowindex;
    var newrow = "<tr data-index=" + rowindex + ">" + $(tr).clone(true).html() + "</tr>";
    $(tr).after(newrow);
    var deletebutton = $(tr).next().find("td").eq(7).find("button").eq(1);
    deletebutton.removeAttr("disabled");
    deletebutton.attr("class", "btn btn-outline btn-danger btn-xs")
}

/**删除*/
function deleteRowsData(tr) {
    $(tr).remove();
}

/**批量下账 */
function batchPosting() {
    var array = $.openx.getSelectedRow();
    var orderArray = [];
    array.forEach(function (row) {
        if(row.topChannelCode != 'POS') {
            orderArray.push(row.orderCode)
        }
    })
    if (orderArray.length < 1) {
        layer.msg("请选择至少一个选项进行下账,且POS渠道订单不能批量下账");
        return;
    }
    $.openx.confirm("已选择" + orderArray.length + "条订单批量下账，营业员将为空，且批号由系统自动选择，可能与实物不符。是否继续？", function () {
        ajax(jot_posting_server + "/posting/postingService", "batchSalePosting")
            .callx({
                orderCodes: orderArray,
                onResult: function (result) {
                    if (result === 0) {
                        layer.msg('下账成功', {time: 1000}, function () {
                            layer.closeAll();
                            //手动刷新表格
                            $.openx.tableRefresh(null, null, true);
                        });
                    } else {
                        layer.msg("有" + result + "笔订单下账失败，请到”下账列表“中进行查看")
                        $.openx.tableRefresh(null, null, true);
                    }
                },
                //请求失败执行
                onError: function (error) {
                    layer.msg("下账失败")
                    $.openx.tableRefresh(null, null, true);
                }
            });
    });

}

//确认下账
function submitKeepAccount() {
    /**提交表单*/
    var array = [];
    $("#goodsInfo").find("tbody tr").each(
        function (i, item) {
            var goods = new Object();
            /**当前行批号*/
            var td = $(item).find("td");
            /**商品编码*/
            goods.goodsCode = $(td).eq(0).text();
            /**商品总数*/
            goods.total = $(td).eq(2).text();
            /**批号*/
            goods.goodsLotNum = $(td).eq(3).find("select[name='lotNumSelect']").find("option:selected").text().trim();
            /**商品数量*/
            goods.goodsNum = $(td).eq(4).find("select[name='amountSelect']").find("option:selected").text().trim();
            goods.exercisePrice = $(td).eq(5).text();
            goods.accountPrice = $(td).eq(6).text();
            goods.flag = false;
            array.push(goods);
            /**定位错误信息位置*/
            $(td).eq(0).attr("class", "tips" + goods.goodsCode);
        });

    for (var i = 0; i < array.length; i++) {
        var w = array[i];
        /**商品数量非空校验*/
        if (!w.goodsNum || w.goodsNum=="--请选择--") {
            layer.tips("商 品 编 码 " + w.goodsCode + " 未 选 择 数 量", ".tips" + w.goodsCode);
            return;
        }
        /**批次号非空校验*/
        if (!w.goodsLotNum || w.goodsLotNum=="--无批次信息--") {
            layer.tips("商 品 编 码 " + w.goodsCode + " 未 选 择 批 次 号", ".tips" + w.goodsCode);
            return;
        }

        var goodsNum = parseFloat(w.goodsNum);//数量
        /**检查批次是否相同校验*/
        var goodlot = w.goodsCode + w.goodsLotNum + w.exercisePrice;//批次
        for (var j = i + 1; j < array.length; j++) {
            /**商品数量非空校验*/
            if (!array[j].goodsNum) {
                layer.tips("商 品 编 码 " + array[j].goodsCode + " 未 选 择 数 量", ".tips" + array[j].goodsCode);
                return;
            }
            /**批次号非空校验*/
            if (!array[j].goodsLotNum) {
                layer.tips("商 品 编 码 " + array[j].goodsCode + " 未 选 择 批 次 号", ".tips" + array[j].goodsCode);
                return;
            }
            /**批次号是否相同*/
            /** 返利促销活动拆行后注释 by wjl */
/*            if (goodlot == (array[j].goodsCode + array[j].goodsLotNum + array[j].exercisePrice)) {
                layer.tips("商 品 编 码 " + w.goodsCode + " 下 账 时 批 次 号 不 能 相 同", ".tips" + w.goodsCode);
                return;
            }*/
        }

        /**商品数量校验*/
        if (!w.flag) {
            w.flag = true;
        } else {
            continue;
        }

        for (var j = i + 1; j < array.length; j++) {
            var nn = array[j];
            if (!nn.flag) {
                if (w.goodsCode == nn.goodsCode && w.exercisePrice == nn.exercisePrice) {
                    nn.flag = true;
                    goodsNum += parseFloat(nn.goodsNum);
                }
            }
        }
        /** 返利促销活动拆行后注释 by wjl */
/*        if (goodsNum > w.total) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 数 量 不 能 超 过 " + w.total + " 个，目 前 为 " + goodsNum + " 个。", ".tips" + w.goodsCode);
            return;
        }
        if (goodsNum < w.total) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 数 量 不 足 " + w.total + " 个，目 前 为 " + goodsNum + " 个。", ".tips" + w.goodsCode);
            return;
        }*/

    }
    var selectUserCode = $("#storeUserSelect").val();
    if (selectUserCode === '') {
        layer.tips("营 业 员 不 能 为 空", '#otherStoreUser');
        return;
    }
    var sex = $('input[name=sex]:checked').val();
    var userCode = selectUserCode.split("-");

    if (selectUserCode === 'other') {
        var inputUserCode = $('#otherStoreUser').val();
        var sp = inputUserCode.split('-');
        if (sp.length != 2 || sp[1].length > 8 || sp[1].length < 1) {
            layer.tips("非 门 店 员 工 填 写 " + inputUserCode + " 不 符 合 要 求", '#otherStoreUser');
            return;
        } else {
            userCode[0] = sp[0];
            userCode[1] = sp[1];
        }
    }
    var patientName = $('#patientName').val();
    var patientPhone = $('#patientPhone').val();
    var patientAge = $('#patientAge').val();
    var patientIDCard = $('#patientIDCard').val();
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    var regPhone1 = /^1\d{10}$/;
    var regPhone2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    if (patientName != undefined && patientName.trim().length > 0) {
        if (patientName.length != 0 && patientName.trim().length < 2 && patientName.trim().length < 10) {
            layer.tips("姓 名 填 写 错 误", '#patientName');
            return;
        }
    }
    if (patientPhone != undefined && patientPhone.trim().length > 0) {
        if (regPhone1.test(patientPhone) == false && regPhone2.test(patientPhone) == false) {
            layer.tips("电 话 号 码 不 符 合 要 求", '#patientPhone');
            return;
        }
    }
    if (patientIDCard != undefined && patientIDCard.trim().length > 0) {
        if (regIdCard.test(patientIDCard) == false) {
            layer.tips("身 份 证 号 码 不 符 合 要 求", '#patientIDCard');
            return;
        }
    }

    if (patientAge != undefined && patientAge.trim().length > 0) {
        if(!isIntNum(patientAge)){
            layer.tips("年 龄 必 须 为 数 字", '#patientAge');
            return;
        }
    }


    var patientAddress = $('#patientAddress').val();
    if (patientAddress != undefined && patientAddress.trim().length > 50) {
        layer.tips("患 者 地 址 不 能 超 过 50 个 字 符", '#patientAddress');
        return;
    }

    //add by zhouwenkai start

    var prescriptionFlag = $('#prescriptionFlag').val();
    console.log("prescriptionFlag="+prescriptionFlag);

    var instrumentFlag = $('#instrumentFlag').val();
    console.log("instrumentFlag="+instrumentFlag);

    if(prescriptionFlag === 'true'){
        // //患者姓名，性别，年龄 必须
        // console.log("我是处方单")
        // if(patientName === undefined || patientName.length==0){
        //     layer.tips("姓 名 必 填", '#patientName');
        //     return;
        // }
        //
        // if(sex === undefined || sex.length==0){
        //     layer.tips("性 别 必 填", '#sexlable');
        //     //alert("患 者 性 别 必 填")
        //     return;
        // }
        //
        // if(patientAge === undefined || patientAge.length==0){
        //     layer.tips("年 龄 必 填", '#patientAge');
        //     return;
        // }
    }


    var customerPhone = $('#customerPhone').val();
    var customerName = $('#customerName').val();

    if(instrumentFlag==='Y'){
        console.log("我是三类医疗")
        if(customerName === undefined ||customerName.length==0){
            layer.tips("顾 客 姓 名 必 填", '#customerName');
            return;
        }

        if(customerPhone === undefined ||customerPhone.length==0){
            layer.tips("联 系 电 话 必 填", '#customerPhone');
            return;
        }else {
            if (regPhone1.test(customerPhone) == false && regPhone2.test(customerPhone) == false) {
                layer.tips("联 系 电 话 不 符 合 要 求", '#customerPhone');
                return;
            }
        }
    }

    //add by zhouwenkai end
    /**下账确认*/

    $.openx.confirm("是否确认下账？", function () {
        var operatorCode = "";
        if (userCode[0] === '') {
            operatorCode = ""
        } else {
            operatorCode = userCode[1];
        }
        var postingModel = new Object();
        postingModel.orderCode = orderCode;
        postingModel.operatorCode = operatorCode;
        postingModel.receiverName = $('#pReceiverName').html();
        postingModel.receiverPhone = $('#pReceiverPhone').html();
        postingModel.prescriptor = $('#pPrescriptor').val();
        postingModel.saleMan = $('#pSaleMan').val();
        postingModel.reviewer = $('#pReviewer').val();
        postingModel.patientName = patientName;
        postingModel.patientPhone = patientPhone;
        postingModel.patientIDCard = patientIDCard;
        postingModel.sex =  sex;
        postingModel.patientAge = patientAge;

        postingModel.customerPhone =  customerPhone;
        postingModel.customerName = customerName;

        postingModel.linkageAddress = patientAddress ;

        postingModel.goods = array;

        console.log("最终post-submitKeepAccount"+JSON.stringify(postingModel));

        ajax(jot_posting_server + "/posting/postingService", "sendSalePosting")
            .callx({
                postingModel: postingModel,
                onResult: function (result) {
                    if (result === 'SUCCESS') {
                        layer.msg('下账成功', {time: 1000}, function () {
                            layer.closeAll();
                            //手动刷新表格
                            $.openx.tableRefresh(null, null, true);
                        });
                    } else {
                        layer.msg("下账失败: " + result);
                    }
                },
                //请求失败执行
                onError: function (error) {
                    layer.msg("下账失败")
                }
            });

    });
}


//*******************以下为格式化表格元素****************/

//是否需要发票
function needInvoiceFormat(value) {
    return value ? "是" : "-"
}

function isIntNum(val){
    var regPos = /^\d+$/; // 非负整数
    if(regPos.test(val)){
        return true;
    }else{
        return false;
    }
}

//格式化订单详情按钮
function operationFormat(value, row) {
    //是否为审方单
    var isRecipe = row.ordonnanceId ? true : false;

    //小票是否已打印
    var ticketPrint = row.ticketPrinted;

    //处方单是否已打印
    var printPrescription = row.prescriptionPrinted;

    //用法用量是否已打印
    var printUsageAndDosage = row.dosagePrinted;
    //顶级渠道
    var topChannelCode = row.topChannelCode;
    var posisPosting = false;
    if(row.billStatus != null && row.billStatus == 'true'){
        posisPosting = true;
    }


    //是否已下账
    var isPosting = (row.posCode && row.posCode !== '000000') ? true : false;

    //订单状态
    var orderStatus = row.stateCode;

    //小票能否打印
    var enableTicketPrint = (row.stateCode === 'DELIVERY_WAITING' || row.stateCode === 'RECEIVE_WAITING' || row.stateCode === 'ORDER_FINISH') && row.billType !== 'REQUEST' ? true : false

    //自提是否可操作
    var selfPick = row.stateCode === 'DELIVERY_WAITING' && row.deliveryType === 'SELF_PICK' && row.billType !== 'REQUEST';

    var billType = row.billType;

    var html = "";
    // 打印小票  如果说已打印则显示重打按钮操作
    if (row.topChannelCode === 'HXYG') {
        html += "<a href=\'javascript:void(0)\' onclick =\'javascript:printTicketNotify(" + (enableTicketPrint ? JSON.stringify(row) : null) + ")\'>" +
            "<button type='button'   class='btn btn-outline btn-primary btn-xs'>仅打小票</button> " +
            "<a>";
    }

    html += "<a href=\'javascript:void(0)\' onclick =\'javascript:printlnTicketNotify(" + (enableTicketPrint ? JSON.stringify(row) : null) + ")\'>" +
        "<button type='button'" + (enableTicketPrint ? "" : "disabled") + "   class='btn btn-outline " + (enableTicketPrint ? 'btn-primary' : 'btn-default') + " btn-xs'>" + (ticketPrint ? "<font color='#f7a54a'>重打小票</font>" : "打印小票") + "</button> " +
        "<a>";

    //自提控制
    html += "<a href=\'javascript:void(0)\' onclick =\'javascript:orderFinished(" + (selfPick ? JSON.stringify(row) : null) + ")\'>" +
        "<button type='button'" + (selfPick ? "" : "disabled") + "   class='btn btn-outline " + (selfPick ? 'btn-primary' : 'btn-default') + " btn-xs'>标记自提</button> " +
        "<a>";

    // //打印处方单 不需要打印处方单的情况 把按钮置灰 并禁用， 如果说已打印则显示重打按钮操作
    // html += "<a href=\'javascript:void(0)\' onclick =\'javascript:printPrescription(" + (isRecipe ? JSON.stringify(row) : null) + ")\'>" +
    //     "<button type='button'" + (isRecipe ? "" : "disabled") + "   class='btn btn-outline " + (isRecipe ? 'btn-primary' : 'btn-default') + " btn-xs'>" + (printPrescription ? "<font color='#f7a54a'>重打处方单</font>" : "打印处方单") + "</button> "
    // "<a>";

    // //打印用法用量  不需要打印用法用量的情况 把按钮置灰 并禁用， 如果已打印则显示重打按钮操作
    // html += "<a href=\'javascript:void(0)\' onclick =\'javascript:printUsageAndDosage(" + (isRecipe ? JSON.stringify(row) : null) + ")\'>" +
    //     "<button type='button'" + (isRecipe ? "" : "disabled") + "   class='btn btn-outline " + (isRecipe ? 'btn-primary' : 'btn-default') + " btn-xs'>" + (printUsageAndDosage ? "<font color='#f7a54a'>重打用法用量</font>" : "打印用法用量") + "</button> "
    // "<a>";

    if(topChannelCode =="POS"){//如果是智能门店协调的POS渠道走独立的界面
        //先屏蔽该功能,等语音提醒功能上线后开发该功能。
        if(allowConsortGoBack) {
            if(orderStatus == 'DELIVERY_WAITING' && billType == 'CONSORT' ) {
                html += "<a href=\'javascript:void(0)\' onclick =\'javascript:goBack(" +  JSON.stringify(row)  + ")\'>" +
                    "<button type='button'" + "   class='btn btn-outline btn-primary btn-xs'" + "> 拒绝发货</button> "
                "<a>";
            }
        }
        if(allowTransferReject) {
            if(orderStatus == 'DELIVERY_WAITING' && billType == 'TRANSFER' ) {
                html += "<a href=\'javascript:void(0)\' onclick =\'javascript:rejectTransfer(" +  JSON.stringify(row)  + ")\'>" +
                    "<button type='button'" + "   class='btn btn-outline btn-primary btn-xs'" + "> 拒绝调货</button> "
                "<a>";
            }
        }
        //下账按钮是否显示
        if (orderStatus == 'ORDER_FINISH' || orderStatus == 'RECEIVE_WAITING' ) {
            html += "<a href=\'javascript:void(0)\' onclick =\'javascript:queryPosOrderPostingDetail(" + (!posisPosting ? JSON.stringify(row) : null) + ")\'>" +
                "<button type='button'" + (!posisPosting ? "" : "disabled") + "   class='btn btn-outline " + (!posisPosting ? 'btn-primary' : 'btn-default') + " btn-xs'> " + (!posisPosting ? "确定协调批号" : "确定协调批号") + "</button> "
            "<a>";
        } else {
            html += "<a href=\'javascript:void(0)\'><button type='button' disabled  class='btn btn-outline btn-default btn-xs'>确定协调批号</button><a>";
        }
    }else{
        //下账按钮是否显示
        if ((orderStatus == 'ORDER_FINISH' || orderStatus == 'RECEIVE_WAITING') && billType !== 'REQUEST') {
            html += "<a href=\'javascript:void(0)\' onclick =\'javascript:queryPostingDetail(" + (!isPosting ? JSON.stringify(row) : null) + ")\'>" +
                "<button type='button'" + (!isPosting ? "" : "disabled") + "   class='btn btn-outline " + (!isPosting ? 'btn-primary' : 'btn-default') + " btn-xs'> " + (!isPosting ? "下账" : "下账") + "</button> "
            "<a>";
        } else {
            html += "<a href=\'javascript:void(0)\'><button type='button' disabled  class='btn btn-outline btn-default btn-xs'>下账</button><a>";
        }
    }

    return html;
}

function billTypeFormat(value, row) {
    if(row.billType == 'TRANSFER') {
        return "智能协调(非销售驱动)";
    }
    if(row.billType == 'CONSORT') {
        return "智能协调(销售驱动)";
    }
    return "线上订单";
}
//标记已完成
function orderFinished(row) {
    $.openx.confirm('确定标记已自提？', function () {
        $X("/order/operateService", "finishOrder").callx({
            orderCode: row.orderCode,
            operatorId: param.userCode ? param.userCode : "",
            remark: "自提手动标记订单",
            onResult: function (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg(JSON.parse(error).message);
            }
        });
    });
}

function resetForm() {
    $('#queryForm')[0].reset();
    var laydate = layui.laydate;
    console.log(laydate.now().split(' ')[0]);
    document.getElementById('createStartTime').value = laydate.now(-1).split(' ')[0] + ' 00:00:00';
    document.getElementById('createEndTime').value = laydate.now().split(' ')[0] + ' 23:59:59';

    var data = $.openx.getJsonObj(formId);
    param.order = data;
    $.openx.initTable("table", url, param);
    $.openx.query();
}
/**
 * 格式化查看订单详情
 */
function showOrderDetailFormat(value, row) {
    return "<a href=\'javascript:void(0)\' title='\点击查看订单详情\' style = '\color:#000000;text-decoration:underline;\' onclick =\'javascript:showOrderPickDetail(" + JSON.stringify(row) + ")\'><b>" + row.orderCode + "</b><a>";
}

/**
 * 格式化下单时间
 */
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value), "yyyy-MM-dd hh:mm");
}

/**
 * 格式化备注

 */
function remarkFormat(value, row) {
    if (row.remark) {
        if (row.remark.length > 10) {
            return "<a id='" + row.orderCode + "' onclick='showAll(" + JSON.stringify(row) + ");'>" + row.remark.substring(0, 10) + "\n..." + "</a>";
        } else {
            return row.remark;
        }
    }
    return "-";
}

function showAll(row) {
    layer.tips(row.remark, '#table a[id="' + row.orderCode + '"]', {
        tips: [4, '#78BA32'],
        area: ['auto', 'auto']
    });
}

/**
 * 退货入库按钮确认操作

 function refundOrderStockConfirm(orderCode) {
    $X("/order/queryService", "getOrderRefundByOrderCode").callx({
        orderCode: orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            orderDetail.refundOrder = result;
            var html = $.openx.innerHtml('returnOrderTpl');
            laytpl($.openx.innerHtml('returnOrderTpl')).render(orderDetail, function (html) {
                var index = $.openx.openLayer(['940', '530'], '确认退货申请', html, true, function () {
                    //确认操作
                    layer.confirm('请确认物品完好，是否退货入库？', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        doRefundOrderStock(orderCode);
                    }, function () {
                        layer.closeAll('loading');
                    });
                });
            });
        },
        //请求失败执行
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}
 */
function doRefundOrderStock(orderCode) {
    $X("/order/operateService", "refundOrderStorage").callx({
        orderCode: orderCode,
        onResult: function (result) {
            layer.msg('退货单处理成功', {time: 1000}, function () {
                layer.closeAll();
                //手动刷新表格
                $.openx.tableRefresh(null, null, true);
            });
        },
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}

function warehouseCodeFormatter(value, row) {
    if (value) {
        return "<a   style = '\color:#000000;text-decoration:underline;\' onclick='javascript:queryWarehouseDetail(" + JSON.stringify(row) + ");'><b>" + row.warehouseCode + "</b></a>";
    }
    return "-"

}

function queryWarehouseDetail(row) {
    $X("/wms/physicalWMSService", "queryDetail").callx({
        warehouseCode: row.warehouseCode,
        onResult: function (data) {
            if (data) {
                if (data.status === 'CLOSE') {
                    data.status = '停业';
                } else if (data.status === 'OPEN') {
                    data.status = '营业';
                }
                if (data.type === 'SHOP') {
                    data.type = '门店';
                } else if (data.type === 'MAIN') {
                    data.type = '大仓';
                }
                var innerHtml = $.openx.innerHtml('warehouseDetail');
                laytpl(innerHtml).render(data, function (html) {
                    $.openx.openLayer(['auto', 'auto'], '查询仓库详情', html, false);
                });
            } else {
                layer.msg("无详情信息")
            }
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }

    });
}

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

//乘法函数
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    // alert(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month == '1' || month == '3' || month == '5' || month == '7' || month == '8' || month == '10' || month == '12') {
        monthDays = 31;
    } else if (month == '4' || month == '6' || month == '9' || month == '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

function getSystemParam() {
    ajax(x_jot_sic_server + "/SysParamService", "getSystemParam").callx({
        onResult: function (data) {
            if (data) {
                allowConsortGoBack = data.allowConsortGoBack;
                allowTransferReject = data.allowTransferReject;
            }
        },
        onError: function (error) {
        }
    });
}
/**
 * New Openx js client, more modern ! 2015-05-19
 */
function ajax(mapping, method) {
    var _m = mapping;
    var _t = method;
    this.callx = function (data, timeout) {
        var url = _m + '/' + _t;
        if (openx.isNull(data)) {
            data = {};
        }
        openx.invoke(url, openx.conf()['type'], data, timeout, data.onResult, data.onError);
    };
    return this;
}



//
// //查询营业员信息
// let orderRow;
// function querySalesCodes(row) {
//     orderRow = row;
//     var html = $.openx.innerHtml('salesCodesTpl');
//     ajax(jot_posting_server + "/posting/postingQueryService", "querySalesCodes").callx({
//         orderCode: row.orderCode,
//         onResult: function (result) {
//             layer.closeAll('loading');
//             result.orderCode = row.orderCode;
//             laytpl($.openx.innerHtml('salesCodesTpl')).render(result, function (html) {
//                 $.openx.openLayer(null, '打印小票', html, true);
//             });
//         },
//         onError: function (error) {
//             layer.msg(error.msg);
//         }
//     });
// }
//
// /**选择营业员*/
// function submitSalesCode(orderCode) {
//     var selectUserCode = $("#salesCodeSelect").val();
//     if (selectUserCode === '') {
//         layer.tips("营 业 员 不 能 为 空", '#salesCodeSelect');
//         return ;
//     }
//     saveOperatorCode(orderCode,selectUserCode);
//     layer.closeAll();
//     printlnTicket(orderRow);
//
// }
//
// function saveOperatorCode(orderCode, operatorCode) {
//     var postingModel = {};
//     postingModel.orderCode = orderCode;
//     postingModel.operatorCode = operatorCode;
//     ajax(jot_posting_server + "/posting/postingService", "savePostingModel").callx({
//         postingModel: postingModel,
//         onResult: function (result) {
//             console.info("保存下账数据成功");
//         },
//         //请求失败执行
//         onError: function (error) {
//             console.info(error);
//             layer.msg("保存下账数据失败: " + error);
//         }
//     });
// }
